<template>
  <div id="app">
    <Toast v-if="!isInit" :message="$lang.loading"></Toast>
 
    <div class="toast-wraper" v-if="!offline" @click="refshloading">
      <div class="showloading">
        <img class="toastImg" :src="lineImg[eIndex]" alt="">
        <div style="margin: 12px 32px 0 32px;" >
          <p class="fail-tip">{{ errorEmailRight[eIndex] }}</p>
          <p v-if ="!offline&&eIndex == 0" class="permision-tip">{{ $lang.permissions }}</p>
        </div>
      </div>
    </div>
    
    <router-view v-if="isInit && offline" />
  </div>
</template>
<script>
import Toast from "@/plugins/Toast/Toast";
import { mapMutations, mapGetters } from "vuex";
import {
  // getFileExt,
  getUrlParam,
  isMobile,
  changeTabRead,
} from "@/utils/helper.js";
export default {
  components: {
    Toast,
  },
  data() {
    return {
      activeNames: ["1"],
      isInit: false,
      cookie: null,
      offline: true,
      watermarkWidth: "176px",
      watermarkHeight: "119px",
      res:null,
      lineImg:[require('@/assets/icon/permissions.png'),
               require('@/assets/icon/404.png'),
               require('@/assets/icon/serveError.png')],
      errorEmailRight:[this.$lang.errorEmailRight,
                       this.$lang.off404,
                       this.$lang.serveerror ],
      eIndex:0
    };
  },
  computed: {
    ...mapGetters(["mailType"]),
    currentPath() {
      return this.$route.path;
    },
  },
  watch: {
    $route: {
      handler: function (newV) {
        try {
          if (newV.name === "EmailDetail") {
            document
              .getElementById("view")
              .setAttribute(
                "content",
                "user-scalable=yes, width = device-width, initial-scale = 1.0"
              );
          } else {
            document
              .getElementById("view")
              .setAttribute(
                "content",
                "user-scalable=0, width = device-width, initial-scale = 1.0"
              );
          }
        } catch {
          console.error("动态缩放失败");
        }
      },
      deep: true,
    },
  },
  created() {
    console.warn("进入App.vue");
    console.warn(location.href);
    this.getImgObj()
    // console.warn('base_r', process.env) //查看当前shell的环境变量，查看 BASE_URL：'oppo-mail'
    this.getToken();
    // this.getticket()
    this.cancleNotification();
    this.getcookie();
    window.qing.call("setBounce", { enable: 0 });
    // window.qing.call("setWebBottomInset", {
    //   show: true, //底部增加34偏移量
    //   success: function (res) { 
    //     console.warn(res,"调用适配iponeX的桥增加34偏移量");
    //   },
    // });

    // if (localStorage.getItem("_mailStore")) {
    //   this.$store.replaceState(
    //     Object.assign(
    //       {},
    //       this.$store.state,
    //       JSON.parse(localStorage.getItem("_mailStore"))
    //     )
    //   );
    // }
  },
  mounted() {},
  methods: {
    // 图片进行预加载
    getImgObj(){
      const imgs = [
        require('@/assets/networkwarn.svg'),
        require('@/assets/toastIcon.svg')
      ]
      for (let index = 0; index < imgs.length; index++) {
        let imgObj = new Image(); // 创建图片对象
            imgObj.src = imgs[index];
      }
      console.warn('图片加载完了');
    },
    // 加载失败时刷新页面
    refshloading(){
      if(!this.offline && this.eIndex != 0 ){
        location.reload()
        // this.offline = true
      }
      console.warn("点击屏幕了");
    },
    toJSON() {}, //屏蔽下拉刷新vue-lottie动效报错
    ...mapMutations(["SAVEUSERINFO", "SAVEMAILTYPE", "SAVEFOLDERINFO"]),
    // 续费cookie
    getcookie() {
      console.warn("getCookie");
      clearInterval(this.getcooking);
      this.cookie = setInterval(() => {
        this.Api.cookrefresh();
      }, 600000);
    },
   
    // 水印生成
    watermarkImg(
      // width = this.watermarkWidth,
      // height = this.watermarkHeight,
      // textAlign = "center",
      // textBaseline = "middle",
      // font = "14px",
      // rotate = "350",
      // zIndex = 1000
      str,productName
    ) {
      {
        // var args = arguments[0];
        var canvas = document.createElement("canvas");
        // canvas.setAttribute("width", width);
        // canvas.setAttribute("height", height);
        var ctx = canvas.getContext("2d");
        var deg = 15 * Math.PI / 180
        var text1 = ctx.measureText(productName || 'TeamTalk')
        var text2 = ctx.measureText(str)
        var space1 = 10
        var space2 = 90

        var textX = Math.cos(deg) * (text1.width + space2 + text2.width + space2)
        canvas.width = textX
        canvas.height = Math.sin(deg) * (text1.width + space2 + text2.width + space2)
        ctx.fillStyle = 'rgba(0,0,0,.05)' //#e2e4e7
        ctx.font = 'normal 12px Arial,Microsoft YaHei,Microsoft JhengHei,Helvetica Neue,sans-serif'
        ctx.translate(0, canvas.height)
        ctx.rotate(-deg)
        ctx.fillText(productName || 'TeamTalk', space1, 0)
        ctx.fillText(str, space1 + text1.width + space2,0 )
        localStorage.setItem("watermarkImg", canvas.toDataURL());
        // ctx.textAlign = textAlign;
        // ctx.textBaseline = textBaseline;
        // ctx.font = font;
        // ctx.fillStyle = "#F0F1F4";
        // ctx.rotate((Math.PI / 180) * rotate);
        // ctx.fillText(
        //   JSON.parse(localStorage.getItem("omail_userInfo")).waterMark.secondWatermark,
        //   -5,
        //   30
        // );
        // ctx.fillText(
        //   JSON.parse(localStorage.getItem("omail_userInfo")).waterMark.firstWatermark,
        //   25,
        //   60
        // );
        // var base64Url = canvas.toDataURL();
      }
      // window.__canvasWM = __canvasWM;
    },

    //  cancleNotification取消待办
    async cancleNotification() {
      let newUrl = decodeURI(getUrlParam("officeemail", window.location.href));
      console.warn(newUrl, "这是解码路径");
      let sourceIdStar = newUrl.indexOf("=") + 1;
      let sourceIdEnd = newUrl.indexOf("&");
      let sourceId = newUrl.substring(sourceIdStar, sourceIdEnd);
      console.warn("这是sourceId", sourceId);

      let newrouter =
        encodeURI(getUrlParam("webLink", newUrl)).replace(/\+/g, "%2B") +
        "&exvsurl=" +
        getUrlParam("exvsurl", newUrl) +
        "&viewmodel=" +
        getUrlParam("viewmodel", newUrl);
      console.warn("sourceId", sourceId);
      console.warn("取消待办路径", window.location.href);
      console.warn("新路径", newrouter);
      if (sourceId.length) {
        console.error(33333);
        try {
          let res = await this.Api.notificationCancle(sourceId);
          console.warn("待办返回", res);
          console.warn("待办传参数", sourceId);
        } catch {
          this.$toast(this.$lang.cancleNotification);
        }
        let type = isMobile();
        console.error(type);
        if (!type) {
          window.location.href = newrouter;
        } else {
          console.error(window.location.href);
          // this.$router.push(window.location.href.split("#")[1]);
          // console.warn(window.location.href.split("#")[1]);
        }
      }
    },

    // 设置头部
    // setHomeMenu() {
    //   window.qing.call("setHomePopMenu", {
    //     items: [
    //       { callbackId: "id1", title: "页签1" },
    //       { callbackId: "id2", title: "页签2" },
    //       {
    //         callbackId: "id3",
    //         title: "页签3",
    //         // items: [{ callbackId: "id4", title: "页签4" }],
    //       },
    //     ],
    //     success(res) {
    //       console.warn("success setHomeMenu --", res);
    //     },
    //     error(res) {
    //       console.warn("error setHomeMenu --", res);
    //     },
    //   });
    // },

    /*
     *请求并保存token、水印、jobNo
     */
    async getToken() {
      // this.setHomeMenu()
      try {
       const res = await this.getInfo()
       console.warn("url上获取的ticket请求的数据success",res);
       const {sassOffice} = res?.data?.data
              console.warn("ticket请求的数据success",res);
              // if(!sassOffice){
              //   this.offline = false; 
              // }
        // this.isInit = true;
      } catch(e){
          // this.showApp = false
          // this.offline = false;
          console.error("base/index 接口失败",e);
          try{
              // 获取人员信息
              const info = await this.getTicket()
            // console.warn("打印人员信息",info);
              let newticket = await this.Api.getticket(info.data.eid,info.data.openId)
              console.warn('newticket',newticket);
              localStorage.setItem("ticket",newticket.data.data)
              console.warn("当前info",newticket.data.data);
              const res = await this.getInfo()
              const {sassOffice} = res?.data?.data
              console.warn("通过新获取的ticket请求的数据success",res);
              if(!sassOffice){
                this.offline = false; 
              }
              localStorage.removeItem('ticket');
              // console.warn("二次调用时res",res);
            // this.offline = false;
          }catch(e){
            // 处理网络状态错误
            if(e == 404){
              this.eIndex = 1
            }else if (e == 500){
              this.eIndex = 2
            }else {
              this.eIndex = 0
            }
            this.offline = false;
            console.error("二次接口调用失败",e,this.eIndex);
          }
          }
      //关闭加载中的toast 
      this.isInit = true;     
    },
    // 调用人员信息桥
    async getTicket(){
      return new Promise((reslove, reject) =>{
        qing.call("getPersonInfo",{
        success:function(res){
          // console.warn("打印人员信息桥",res);
          reslove(res)
          },
        error:function(e){
          reject(e)
        }
      })
      // let _that = this 
      // qing.call("getPersonInfo",{
        // success:function(res){
        //  _that.res = res?.data
        //  请求ticket
        //  _that.Api.getticket(_that.res.eid,_that.res.openId).then(res =>{
          //  console.warn(res.data.data);
          //  localStorage.setItem("ticket",res.data.data)
          //  请求数据及鉴权
          //  _that.Api.getToken()
          //  location.reload()
          //  localStorage.setItem("ticket",null)
        //  })
          // console.warn("二次调用时res",res);
          // console.warn(_that.res.eid,_that.res.openId)
        // }
      })
    },
    /**
     * 离开页面清空localStorage
     */
    // clearLocalStorage() {
    //   // localStorage.removeItem('_mailStore')
    // },
    /**
     * 保存用户信息到localstoreage
     */
    // saveTolocalStoreage() {
    //   // alert(document.visibilityState)
    //   localStorage.setItem("_mailStore", JSON.stringify(this.$store.state));
    // },

    // dynamic font-size
    // 获取用户数据及鉴权
    async getInfo(){
      try{
      const res = await this.Api.getToken();
      const { success } = res?.data;
      if (success) {
        setTimeout(() => {
          changeTabRead();
        }, 3000);
        this.SAVEUSERINFO(res?.data?.data);
        this.SAVEMAILTYPE("all");
        this.SAVEFOLDERINFO({
          type: "all",
          folderId: "inbox",
          customName: "all",
        });
        this.watermarkImg(JSON.parse(localStorage.getItem("omail_userInfo")).waterMark.secondWatermark,JSON.parse(localStorage.getItem("omail_userInfo")).waterMark.firstWatermark);
      }
      return res
      }catch(e){
        console.warn("调试404与500",e);
        return e
      }
    },
    setFontSize() {
      document.getElementsByTagName("html")[0].style.fontSize =
        document.body.clientWidth / 10 + "px";
      this.watermarkWidth = document.body.clientWidth / 4 + "px";
    },
  },
};
</script>
<style lang="less" scoped>
#app {
  height: 100%;
  width: 100%;
  background-color: white;
  .skeleton-wraper {
    height: 100%;
    padding: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    hr {
      background-color: #f2f3f5;
      height: 1px;
      border: none;
    }
    /deep/ .van-skeleton__row {
      width: 100% !important;
    }
  }
}

.toast-wraper{
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    background: #fff;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    -webkit-box-pack: center;
    -webkit-justify-content: center;
    justify-content: center;
    -webkit-box-align: center;
    -webkit-align-items: center;
    align-items: center;
    z-index: 99999;
    .showloading{
      min-width: 140px;
      height: auto;
      text-align: center;
    }
    .toastImg{
      width: 140px;
      height: 140px;
    }
    .fail-tip{
      margin: 0 auto;
      min-width: 70%;
      color: #969799;
      word-break: break-all;
      font-size: 0.3733338636356rem;
      color: #969799;
      text-align: center;
      line-height: calc(1.5 * 0.3733338636356rem );
      font-weight: 400;
    }
    .permision-tip{
      font-size: 0.3200004545448rem;
      color: #CDCFD1;
      letter-spacing: 0;
      text-align: center;
      line-height: 0.48000068181719996rem;
      font-weight: 400;
      margin-top:0.2133336363632rem;
    }
}
</style>
